<template>
    <div>
        <div class="login" v-if="unbind">
            <div class="top">
                <img alt="logo" :src="$getImageUrl(logoUrl)">
            </div>
            <div class="login-bg" :style="{'background-image': `url(${$getImageUrl(bgUrl)})`}">
                <div class="login-container">
                    <div class="login-container-layout">
                        <div class="login-type">
                            <div class="login-type-name">{{loginTypes[loginType]}}</div>
                        </div>
                        <div id="login-by-disabled" v-if="loginType === 'disabled'">
                            <el-form :model="info" :rules="rules" label-position="left" label-width="0px" ref="form">
                                <el-form-item style="width:100%;">
                                    浏览器已禁用cookie，请在浏览器设置中启用cookie后刷新本页面重新尝试登录。
                                </el-form-item>
                            </el-form>
                        </div>
                        <div id="login-by-username" v-if="loginType === 'username'">
                            <el-form :model="info" :rules="rules" label-position="left" label-width="0px" ref="form">
                                <el-form-item class="mb22" prop="username">
                                    <el-input auto-complete="off" class="input" placeholder="用户名" type="text"
                                              v-model.trim="info.username"/>
                                </el-form-item>
                                <el-form-item class="mb22" prop="password">
                                    <el-input auto-complete="off" class="input" placeholder="请输入密码" type="password"
                                              v-model.trim="info.password"/>
                                </el-form-item>
                                <el-form-item style="width:100%;">
                                    <el-button :loading="logging" @click.native.prevent="passwordSubmit" class="btn"
                                               style="width:100%;" type="primary">绑定
                                    </el-button>
                                </el-form-item>
                            </el-form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script lang="ts">
  import ControlPanelApi from '@/api/user/controlPanelApi';
  // api
  import DingTalkControlPanelApi from '@/api/user/dingTalkControlPanelApi';
  import BindRequest from '@/structure/bindRequest';
  import LoginResponse from '@/structure/loginResponse';
  // structure
  import {LoginType} from '@/structure/loginType';
  import Menu from '@/structure/menu';
  import User from '@/structure/user';
  // utils
  import MenuUtil from '@/utils/menu';
  import UserUtil from '@/utils/user';
  import * as dd from 'dingtalk-jsapi';
  import {ElForm} from 'element-ui/types/form';
  import {Component, Vue} from 'vue-property-decorator';
  import {RouteConfig} from 'vue-router';

  @Component
  export default class Page extends Vue {
    public logoUrl: string = '';
    public bgUrl: string = '';
    public unbind: boolean = false;
    public code: string = '';
    public thirdPartyId: string = '';

    public routers: RouteConfig[] = [];
    public logging: boolean = false;
    public loginType: LoginType = 'username';
    public loginTypes: { [key: string]: string } = {
      disabled: '请启用cookie',
      username: '账号绑定'
    };
    public info: BindRequest = new BindRequest();
    public rules: any = {
      username: [
        {
          required: true,
          message: '请输入用户名'
        }
      ],
      password: [
        {
          required: true,
          message: '请输入密码'
        }
      ]
    };

    public created() {
      this.logoUrl = process.env.VUE_APP_LOGIN_PAGE_LOGO;
      this.bgUrl = process.env.VUE_APP_LOGIN_PAGE_BG;
      if (!navigator.cookieEnabled) {
        this.loginType = 'disabled';
        return;
      }

      const corpId = process.env.VUE_APP_DING_TALK_CORPID;
      if (!corpId) {
        this.$message.error('企业ID无效');
        return;
      }

      if (dd.env.platform === 'notInDingTalk') {
        this.$message.error('请在钉钉客户端中打开');
        return;
      }

      dd.ready(() => {
        dd.runtime.permission.requestAuthCode({
          corpId
        }).then(({code}) => {
          this.code = code;
          this.toLogin();
        });
      });
    }

    public toLogin() {
      DingTalkControlPanelApi.loginByCode(this.code).then((res) => {
        this.unbind = res.accessToken === undefined;
        this.thirdPartyId = res.thirdParty.thirdPartyId;

        if (this.unbind) {
          this.info.thirdPartyId = this.thirdPartyId;
        } else {
          this.login0(res);
        }
      });
    }

    public refreshMenus(menus: Menu[]): void {
      MenuUtil.set(menus);
      MenuUtil.format(this.routers, menus);
    }

    public passwordSubmit(): void {
      (this.$refs.form as ElForm).validate((valid) => {
        if (!valid) {
          return;
        }

        this.logging = true;

        DingTalkControlPanelApi.bind(this.info)
          .then((userData) => this.login0(userData))
          .catch((err) => this.afterPasswordSubmit(err));
      });
    }

    public afterPasswordSubmit({errorCode, message}: any): void {
      this.logging = false;
      if (errorCode > 900 && errorCode <= 999) {
        this.$message.error(message);
      }
    }

    public login0(userData: LoginResponse<User>): void {
      UserUtil.set(userData);
      this.loadMenu();
    }

    public loadMenu() {
      ControlPanelApi.getMenus().then((menus) => {
        this.refreshMenus(menus);
        this.$router.addRoutes(this.routers);

        this.$router.push({
          name: 'ControlPanel_PersonalData'
        });
      });
    }
  }
</script>
<style lang="scss" scoped>
    @import "@/assets/login.scss";
</style>
